﻿using System.Net.Mail;
using System.Windows.Forms;

namespace Keyer.Util.mail
{
    public class MailHelper
    {
        SmtpClient smtpClient;
        //邮件实体类，包含用户名密码  
        MailModel mail;
        UserModel to;
        public MailHelper()
        {
        }
        public MailHelper(MailModel mail, UserModel t)
        {
            smtpClient = new SmtpClient();
            this.mail = mail;
            this.to = t;
        }
        public void send()
        {
            MailMessage msg = null;
            smtpClient.Credentials = new System.Net.NetworkCredential(mail.from.Send_Address.Address, mail.from.password);//设置发件人身份的票据    
            smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
            smtpClient.Host = "smtp." + mail.from.Send_Address.Host;
            msg = mail.GetMail();
            try
            {               
                //msg.To.Add(to.Send_Address.Address);
                foreach (string str in to.mailAddress)
                {
                    if (!string.IsNullOrEmpty(str))
                    {
                        msg.To.Add(str);
                        smtpClient.Send(msg);
                    }                    
                }              
                MessageBox.Show("发送成功");
            }
            catch (SmtpException err)
            {
                //如果错误原因是没有找到服务器，则尝试不加smtp.前缀的服务器  
                if (err.StatusCode == SmtpStatusCode.GeneralFailure)
                {
                    try
                    {
                        //有些邮件服务器不加smtp.前缀  
                        smtpClient.Host = null;
                        smtpClient.Send(mail.GetMail());
                    }
                    catch (SmtpException err1)
                    {
                        MessageBox.Show(err1.Message, "发送失败");
                    }
                }
                else
                {
                    MessageBox.Show(err.Message, "发送失败");
                }
            }
            finally
            {
                //及时释放占用的资源  
                msg.Dispose();
            }
        }
    }
}
